import {Pagination} from "antd";
import {useEffect, useState} from "react";
import {LIST_PAGE_PARAM_KEY, LIST_PAGE_SIZE, LIST_PAGE_SIZE_PARAM_KEY} from "../constant";
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";

type PropsType = {
    total: number
}
export const ListPage = (props: PropsType) => {
    const {total} = props
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(LIST_PAGE_SIZE);

    const nav = useNavigate()
    const {pathname} = useLocation()

    const [searchParams] = useSearchParams()

    useEffect(() => {
        const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
        setPage(page)
        const pageSize = parseInt(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY) || '') || LIST_PAGE_SIZE;
        setPageSize(pageSize)
    }, [searchParams])

    const handlePageChange = (page: number, pageSize: number) => {
        searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
        searchParams.set(LIST_PAGE_SIZE_PARAM_KEY, pageSize.toString())
        nav({
            pathname,
            search: searchParams.toString()
        })
    }
    return <Pagination current={page} onChange={handlePageChange} pageSize={pageSize} total={total}/>;
}

